package com.example.hotHub.utils;

import com.example.hotHub.cnst.CommonConst;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.ResourceLoader;

import java.io.*;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class FileUtils {

    public static String url2File(String videoUrl, String preStr) {
        try {

            int bytesum = 0;
            int byteread = 0;

            URL url = new URL(videoUrl);
            URLConnection conn = url.openConnection();
            InputStream inStream = conn.getInputStream();

            String[] paths = url.getPath().split("/");
            String filePath = "/video/bili/" + preStr + paths[paths.length - 1];

            ResourceLoader resourceLoader = new DefaultResourceLoader();

            String path = CommonConst.USER_ROOT_HOME + filePath;

            File file = new File(path);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }

            if (!file.exists()) {
                file.createNewFile();
            } else {
                return filePath;
            }

            BufferedOutputStream fs = new BufferedOutputStream(new FileOutputStream(file));

            long startTime = System.currentTimeMillis();

            byte[] buffer = new byte[1024000];
            while ((byteread = inStream.read(buffer)) != -1) {
                bytesum += byteread;
//                System.out.println(bytesum);
                fs.write(buffer, 0, byteread);
            }

            long end = System.currentTimeMillis();

            log.info("爬取bili视频: {}, 视频大小: {}MB, 总用时: {}s", paths[paths.length - 1], new BigDecimal(file.length() * 1.0 / (1024 * 1024)).setScale(2, BigDecimal.ROUND_HALF_UP), (end - startTime) * 1.0 / 1000);

            return filePath;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    public static void removeFile(String dirPath, List<String> ignoreFileNameList) {
//        String dirPath = this.getClass().getClassLoader().getResource("static").getPath() + "/video/bili";

        Map<String, String> ignoreFileNameMap = new HashMap<>();

        for (String ignoreFileName: ignoreFileNameList) {
            ignoreFileNameMap.put(ignoreFileName, "1");
        }

        File dir = new File(dirPath);

        if (dir.exists()) {
            String[] fileNameList = dir.list();
            for (String fileName: fileNameList) {
                if (!ignoreFileNameMap.containsKey(fileName)) {
                    String filePath = dir + "/" + fileName;
                    File file = new File(filePath);
                    file.delete();
                }
            }
        }
    }

}
